/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.hotfixformetroapp.main;

import com.seari.hotfixformetroapp.bean.EmptyStringCell;
import com.seari.hotfixformetroapp.bean.ExcelConfig;
import com.seari.hotfixformetroapp.bean.StationConfig;
import com.seari.hotfixformetroapp.service.StationConfigService;
import com.seari.hotfixformetroapp.utils.ImportExcelUtil;
import com.seari.hotfixformetroapp.utils.MiscTools;
import com.seari.hotfixformetroapp.utils.PositionUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 *
 * @author 60483
 */
//@Component
//@Order(value = 2)
public class HotfixGpsdataOfPosition implements ApplicationRunner
{
    protected Logger logger = LoggerFactory.getLogger(HotfixGpsdataOfPosition.class);
    public static Properties properties;
    public static String configPath = "config.cfg"; //配置文件路径
    private List<StationConfig> stationConfigList;
    private Map<String,StationConfig> stationConfigMap; //站名与config对象对应的键值对
    private final ExcelConfig dataConfig = new ExcelConfig();
    @Autowired
    private StationConfigService stationConfigService;
    
    @Override
    public void run(ApplicationArguments args) throws Exception
    {
        init();
        for (StationConfig stationConfig : stationConfigList)
        {
            double[] result = PositionUtil.gps84_To_Gcj02(Double.parseDouble(stationConfig.getYaxis()), Double.parseDouble(stationConfig.getXaxis()));
            stationConfig.setGcjXaxis(result[1]+"");
            stationConfig.setGcjYaxis(result[0]+"");
            stationConfigService.updateAxisToGcj(stationConfig);
        }
    }
    
    //处理工作薄数据
    private void processWorkBookData(Workbook workbook) throws IOException
    {
        FileOutputStream fileOutputStream = null;
        try
        {
            Sheet sheet = workbook.getSheetAt(dataConfig.getSheetNum());
            for(int i = dataConfig.getDataStartLineNum(); i <= dataConfig.getDataEndLineNum() ; i++)//仅读取起始至结尾的表格数据
            {
                Row row = sheet.getRow(i);
                processRowData(row);
            }
            fileOutputStream = new FileOutputStream(new File(dataConfig.getOutputFileName()));
            workbook.write(fileOutputStream);
        } catch (Exception e)
        {
            e.printStackTrace();
        }finally{
            if(fileOutputStream != null)
            {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
            workbook.close();
        }
    }
    
    //处理行数据
    private void processRowData(Row row)
    {
        try
        {
            for(int i = 0; i < dataConfig.getColumnStrings().length; i++)
            {
                //获取单元格
                Cell cell = row.getCell(i);
                if(cell != null)
                {
                    //强制单元格为String类型数据
                    cell.setCellType(CellType.STRING);
                }else{
                    //单元格为null时，强制单元格为自定义空字符串单元格
                    cell = new EmptyStringCell();
                }
                
                //处理每个单元格数据
                switch(dataConfig.getColumnStrings()[i])
                {
                    //处理故障区间
                    case "area":
                        processCellData(row, cell);
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    //处理单元格数据并编辑回Row（行）
    private void processCellData(Row row,Cell cell)
    {
        String origin = cell.getStringCellValue();
        //区域字段预处理
        origin = origin.replace(" ", "").replace("站厅", "").replace("站台", "").replace("上行", "").replace("下行", "").replace("折返线", "").replace("出入库线", "").replace("存车线", "");
        String[] tempStr = origin.split("—");
        if(tempStr.length > 1)//存在分隔符，可能为多个站名，分别处理
        {
            if(tempStr[0].equals(tempStr[1]))//同名
            {
                combineData(row, cell, guessAxis(tempStr[0]),tempStr[0]);
            }else{
                //不同名时直接着色
                changeRowStyle(row, GpsDataColor.DIFFRENT);
            }
        }else{
            combineData(row, cell, guessAxis(tempStr[0]), tempStr[0]);
        }
    }
    
    //获取X,Y坐标（经纬度）
    private String[] guessAxis(String string)
    {
        String[] result = null;
        if(stationConfigMap.containsKey(string))
        {
            result = new String[]{
                stationConfigMap.get(string).getXaxis(),stationConfigMap.get(string).getYaxis()
            };
        }else if(stationConfigMap.containsKey(string + "站"))//在字符串末尾补全“站”
        {
            result = new String[]{
                stationConfigMap.get(string + "站").getXaxis(),stationConfigMap.get(string + "站").getYaxis()
            };
        }else if(string.startsWith("火车站"))
        {
            result = new String[]{
                stationConfigMap.get("上海火车站站").getXaxis(),stationConfigMap.get("上海火车站站").getYaxis()
            };
        }else
        {
            //do nothing
        }
        return result;
    }
    
    //合并字符串与坐标数据，写入表格
    private void combineData(Row row , Cell cell, String[] axis,String otherString) //otherString作为辅助判断，可不传递
    {
        if(axis != null)
        {
            //创建坐标单元格
            row.createCell(dataConfig.getColumnStrings().length).setCellValue(axis[0]);
            row.createCell(dataConfig.getColumnStrings().length + 1).setCellValue(axis[1]);
        }else{
            if(otherString.length() > 0 )
            {
                if(otherString.contains("控制中心"))
                {
                    changeRowStyle(row, GpsDataColor.CONTROLCENTER);
                }else if(otherString.contains("基地"))
                {
                    changeRowStyle(row, GpsDataColor.BASEMENT);
                }else{
                    //其他情况
                    changeRowStyle(row, GpsDataColor.OTHER);
                }
            }
        }
    }
    
    private void changeRowStyle(Row row,String string)
    {
        CellStyle cellStyle = row.getRowStyle();
        cellStyle.setFillForegroundColor(IndexedColors.valueOf(string).getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        row.setRowStyle(cellStyle);
    }
    
    private void init()
    {
        try
        {
            properties = MiscTools.loadConfig(configPath);
            stationConfigList = stationConfigService.getStationConfig();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
